import { Button, message, Input, Modal, Form, Popconfirm, Select, Switch, Tooltip } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import ProTable from '@ant-design/pro-table';
import { AudioOutlined, AudioMutedOutlined } from '@ant-design/icons';

import {
  getMaterialAssayProjectList,
  addMaterialAssayProject,
  updateMaterialAssayProject,
  removeMaterialAssayProject,
  exportInspection,
  getAudioAll,
} from '@/services';
import { downloadFile } from '@/utils/utils';

const AssayProject = () => {
  const intl = useIntl();
  const actionRef = useRef(null);
  const audioRef = useRef(null);
  const [visible, setVisible] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [updateId, setUpdateId] = useState(null);
  const [queryParams, setQueryParams] = useState();
  const [exportLoading, setExportLoading] = useState(false);
  const [audioList, setAudioList] = useState([]);
  const [audioUrl, setAudioUrl] = useState();

  const [title, setTitle] = useState(
    intl.formatMessage({
      id: 'pages.add',
    }),
  );

  const [form] = Form.useForm();

  const queryAudioAll = async () => {
    const res = await getAudioAll();
    setAudioList(res.data);
  };

  useEffect(() => {
    queryAudioAll();
  }, []);

  const handleAdd = () => {
    setVisible(true);
    setTitle(
      intl.formatMessage({
        id: 'pages.add',
      }),
    );
  };
  const handleExport = async () => {
    setExportLoading(true);
    const res = await exportInspection(queryParams);
    if (res.code === 0) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      downloadFile(res.msg);
    }
    setExportLoading(false);
  };

  const handleUpdate = (record) => {
    setVisible(true);
    setTitle(
      intl.formatMessage({
        id: 'pages.update',
      }),
    );
    setUpdateId(record.id);
    form.setFieldsValue(record);
  };
  const handleRemove = async (record) => {
    const res = await removeMaterialAssayProject({ id: record.id });
    if (res) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      actionRef?.current?.reload();
    }
  };
  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
    setUpdateId(null);
    audioRef.current?.pause();
  };

  const handleOk = async () => {
    await form.validateFields();
    let values = form.getFieldsValue();
    setSubmitting(true);
    const func = updateId ? updateMaterialAssayProject : addMaterialAssayProject;
    const res = await func({
      id: updateId,
      ...values,
    });
    if (res) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      handleCancel();
      actionRef?.current?.reload();
    }
    setSubmitting(false);
  };

  const updateSwitch = async (val, record) => {
    const res = await updateMaterialAssayProject({
      ...record,
      stepSwitch: val,
    });
    if (res) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      actionRef?.current?.reload();
    }
  };

  const columns = [
    {
      title: (
        <FormattedMessage id="pages.dataMain.checkProjectCode" defaultMessage="检测项目编码" />
      ),
      dataIndex: 'inspectionCode',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.dataMain.checkProjectDesc" defaultMessage="检测项目" />,
      dataIndex: 'inspectionDesc',
      ellipsis: true,
    },
    {
      title: <FormattedMessage id="pages.audio.audioUrl" defaultMessage="铃声" />,
      dataIndex: 'audioUrl',
      search: false,
      render: (_, record) => {
        return (
          <Tooltip title={record.audioName}>
            <Switch
              onChange={(val) => playTable(val, record)}
              checkedChildren={<AudioOutlined />}
              unCheckedChildren={<AudioMutedOutlined />}
            />
            <audio id={`audio_${record.audioUrl}`} src={record.audioUrl}></audio>
          </Tooltip>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.audio.stepSwitch" defaultMessage="报警开关" />,
      dataIndex: 'stepSwitch',
      search: false,
      render: (_, record) => {
        return (
          <Switch
            checked={record.stepSwitch}
            onChange={(val) => updateSwitch(val, record)}
            checkedChildren={<FormattedMessage id="pages.open" defaultMessage="开启" />}
            unCheckedChildren={<FormattedMessage id="pages.close" defaultMessage="关闭" />}
          />
        );
      },
    },

    {
      title: <FormattedMessage id="pages.remark" defaultMessage="备注" />,
      dataIndex: 'inspectionRemark',
      search: false,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Button key="update" size="small" onClick={() => handleUpdate(record)} type="success">
          <FormattedMessage id="pages.update" defaultMessage="修改" />
        </Button>,
        <Popconfirm
          key="delete"
          title={<FormattedMessage id="pages.delete_confirm" />}
          onConfirm={() => handleRemove(record)}
        >
          <Button size="small" type="danger">
            <FormattedMessage id="pages.delete" defaultMessage="删除" />
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const queryList = async (params) => {
    setQueryParams(params);
    const res = await getMaterialAssayProjectList({
      ...params,
    });
    if (res) {
      return res;
    }
  };

  const play = () => {
    if (audioRef.current?.paused) {
      audioRef.current?.play();
    } else {
      audioRef.current?.pause();
    }
  };
  const playTable = (checked, record) => {
    let audio = document.getElementById(`audio_${record.audioUrl}`);
    if (audio.paused) {
      checked && audio.play();
    } else {
      !checked && audio.pause();
    }
  };

  return (
    <>
      <ProTable
        headerTitle={intl.formatMessage({
          id: 'pages.dataMain.materialAssayProjectSetting',
          defaultMessage: '化验项目设置',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 100,
        }}
        toolBarRender={() => [
          <Button key="add" type="primary" onClick={handleAdd}>
            <FormattedMessage id="pages.add" defaultMessage="增加" />
          </Button>,
          <Button loading={exportLoading} key="export" onClick={handleExport}>
            <FormattedMessage id="pages.export" defaultMessage="导出" />
          </Button>,
        ]}
        request={(params, sorter, filter) => queryList({ ...params })}
        columns={columns}
      />

      <Modal
        title={title}
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        confirmLoading={submitting}
      >
        <Form form={form} labelCol={{ span: 6 }}>
          <Form.Item
            label={
              <FormattedMessage
                id="pages.dataMain.checkProjectCode"
                defaultMessage="检测项目编码"
              />
            }
            name="inspectionCode"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'pages.dataMain.p_checkProjectCode' }),
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={
              <FormattedMessage id="pages.dataMain.checkProjectDesc" defaultMessage="检测项目" />
            }
            name="inspectionDesc"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'pages.dataMain.p_checkProjectDesc' }),
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={<FormattedMessage id="pages.audio.audioUrl" defaultMessage="铃声" />}
            name="audioId"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'pages.audio.p_select_audioUrl' }),
              },
            ]}
          >
            <Select
              suffixIcon={
                <Tooltip
                  title={<FormattedMessage id="pages.playOrPaused" defaultMessage="播放/暂停" />}
                >
                  <AudioOutlined onClick={play} />
                </Tooltip>
              }
              onChange={(val) => {
                const arr = audioList.filter((item) => item.id === val);
                setAudioUrl(arr[0].audioUrl);
              }}
            >
              {audioList.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.audioName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label={<FormattedMessage id="pages.remark" defaultMessage="备注" />}
            name="inspectionRemark"
          >
            <Input.TextArea rows={4} />
          </Form.Item>
        </Form>
        <audio ref={audioRef} src={audioUrl}></audio>
      </Modal>
    </>
  );
};

export default AssayProject;
